import React, {Component} from 'react';
import ButtonConfirmationBox from './ChildrenComponent/ButtonConfirmationBox';
import TimeShow from './ChildrenComponent/TimeShow';
import UpperPartOfTheForm from './ChildrenComponent/UpperPartOfTheForm';
import moment from 'moment';
import $ from 'jquery';
import 'antd/dist/antd.css';
import './ZhongKongSSCXTJL.css'


class ZhongKongSSCXTJL extends Component {
    constructor(props) {
        super(props);
        this.state = {
            riqi: moment().format('YYYY-MM-DD'),
            timeChose: 0,//选择的班次 0代表1-7 1代表8-15 2代表16-23
            zhibiao: [null, null, null, null, null, null, null, null, null],//从数据库获取的标准
            time: [],
            formData: [],
            average: [],
            ratio: [],
            passRate: [],
            FormData: [{'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},],
            person: '',//传入的值班人员
            isEnable: true,//输入框是否可以进行输入
            date: '',
        }
    }

    /**onRef控制子组件提交表单**/
    onRef = (ref) => {
        this.Form = ref;
    };

    //判定是否已登录，是否有权限
    componentWillMount() {
        fetch('/api/ZhongKS/check', {
            method: 'post',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {
                }
                else{
                    this.props.history.push('/index');
                }
            })
            .catch(error => console.error('Error:', error))
    }

    componentDidMount() {
        /**首先查询当前页面是否有历史纪录并赋值给FormData**/
        const riqi = this.state.riqi;
        const jsondata = {
            'startRiqi': riqi,
            'startXiaoshi': 0,
            'endRiqi': riqi,
            "endXiaoshi": 23,
            'leixing': 'ZKS',
            'zhonglei': 0,
        };
        fetch("/api/ZhongKS/query", {
            method: 'POST',
            credentials: "include",
            body: JSON.stringify(jsondata), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {//判定是否成功
                    let FormData = this.state.FormData;
                    for (let i = 0; i < data['data'].length; i++) {
                        let shuju = data['data'][i]['shuju'];//取出data中的数据
                        let str = shuju.split(',');//去除数据中的string逗号
                        let a = [];//临时的number数据数组
                        for (let i = 0; i < str.length; i++)//将string转换成number
                            a[i] = parseFloat(str[i]);
                        data['data'][i]['shuju'] = a;//数据数组归还给data
                        const xiaoshi = data['data'][i]['xiaoshi'];//按小时排序把数据传给FormData
                        FormData[xiaoshi] = data['data'][i];
                    }
                    // console.log(FormData);
                    this.setState({//传值给FormData和bottomData
                        FormData: FormData,
                        person:window.localStorage.name,
                    });
                }
            })
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));

        /**从服务器获取指标**/
        const leixing = {'leixing': "ZKS"};
        fetch("/api/zhibiao/query", {
            method: 'POST',
            body: JSON.stringify(leixing), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                    if (data['code'] === 0 && data['zhibiao']['leixing'] === 'ZKS') { //判定是否成功
                        let zhi = data['zhibiao']['zhibiao'];//去除指标的逗号
                        const zhibiao = zhi.split(',');
                        let a = [];
                        for (let i = 0; i < zhibiao.length; i++)
                            a[i] = parseFloat(zhibiao[i]);
                        this.setState({
                            zhibiao: a,
                        });
                    }
                }
            )
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));
    }


    /**点击提交数据**/
    handleSubmit = () => {
        this.Form.postAllToHome();
    };

    /**ajax传值结束**/

    /**
     * 响应班次变化
     **/
    handleTimeChose(x) {
        this.setState({
            timeChose: x
        });
    }

    /**传输当前日期到父页面**/
    handleDate(x) {
        this.setState({
            date: x
        });
    }

    /**
     *表单上半部分的数据提交函数
     **/
    handleFormDataChange(formData, average, ratio, passRate, time) {
        this.setState({
            formData: formData,
            average: average,
            ratio: ratio,
            passRate: passRate,
            time: time,
        });
    }

    returnBack = () => {
        this.props.history.push("/index");
    };

    render() {
        return (
            <div style={{padding: '1%'}}>
                <h1 align="center">福石水泥3000t/d中控室烧成系统运行记录</h1>
                {/*表单最上的时间及人员显示*/}
                <TimeShow person={this.state.person} handleTimeChose={this.handleTimeChose.bind(this)}
                          handleDate={this.handleDate.bind(this)}
                />
                <div
                    style={{
                        border: "1px solid black",
                        margin: "10px 20px 10px 20px"
                    }}
                >
                    {/*表单上半部分*/}
                    <UpperPartOfTheForm
                        onRef={this.onRef}
                        riqi={this.state.riqi}
                        zhibiao={this.state.zhibiao}
                        timeChose={this.state.timeChose}
                        person={this.state.person}
                        time={this.state.time}
                        FormData={this.state.FormData}
                        post={this.handleFormDataChange.bind(this)}/>

                </div>
                <div
                    style={{
                        float: "right",
                        margin: "0px 50px 20px 0px",
                        display: "inline-block"
                    }}
                >
                    <ButtonConfirmationBox type="primary" buttonText="提交"
                                           action={this.handleSubmit}
                    />
                </div>
            </div>
        );

    }
}

export default ZhongKongSSCXTJL;